package com.lzx.iteam;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.bean.CloudContact;
import com.lzx.iteam.bean.PhoneNumItem;
import com.lzx.iteam.util.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Megan on 16/1/20.
 */
public class ContactNameCardFragment extends Fragment implements View.OnClickListener {

    private ContactNameCardActivity mActivity;
    private static final String ARG_POSITION = "position";
    private static final String ARG_USERID = "user_id";
    private static final String ARG_GROUPINFO = "group_info";

    private AllDialogUtil mDialogUtil;
    private SendCardShakeListener mShaker;

    private CloudContact mGroupInfo ;
    private View rootView;

    private TextView mTvCompany, mTvName, mTvPosition, mTvPhone, mTvEmail, mTvAddress;


    private String mCompany, mName, mPosition, mPhone, mEmail;
    private StringBuilder mAddress;
    private String mLimitPhone;



    public static ContactNameCardFragment newInstance( CloudContact groupInfo) {
        ContactNameCardFragment f = new ContactNameCardFragment();
        //mGroupInfo = (CloudContact) groupInfo;
        Bundle b = new Bundle();
        b.putSerializable("contact_card",groupInfo);
        f.setArguments(b);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGroupInfo = (CloudContact) getArguments().getSerializable("contact_card");
        mActivity = (ContactNameCardActivity) getActivity();
        mDialogUtil = AllDialogUtil.getInstance(mActivity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        /*if (rootView == null) {
            rootView = inflater.inflate(R.layout.contact_namecard_fragment, container, false);
            mTvCompany = (TextView) rootView.findViewById(R.id.tv_contact_namecard_company);
            mTvName = (TextView) rootView.findViewById(R.id.tv_contact_namecard_name);
            mTvPosition = (TextView) rootView.findViewById(R.id.tv_contact_namecard_position);
            mTvPhone = (TextView) rootView.findViewById(R.id.tv_contact_namecard_phone);
            mTvEmail = (TextView) rootView.findViewById(R.id.tv_contact_namecard_email);
            mTvAddress = (TextView) rootView.findViewById(R.id.tv_contact_namecard_address);
        }
        updataData();
        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }*/

        rootView = inflater.inflate(R.layout.contact_namecard_fragment, container, false);
        mTvCompany = (TextView) rootView.findViewById(R.id.tv_contact_namecard_company);
        mTvName = (TextView) rootView.findViewById(R.id.tv_contact_namecard_name);
        mTvPosition = (TextView) rootView.findViewById(R.id.tv_contact_namecard_position);
        mTvPhone = (TextView) rootView.findViewById(R.id.tv_contact_namecard_phone);
        mTvEmail = (TextView) rootView.findViewById(R.id.tv_contact_namecard_email);
        mTvAddress = (TextView) rootView.findViewById(R.id.tv_contact_namecard_address);
        updataData();
        return rootView;
    }

    public void updataData() {
        Log.i("ContactNameCardFragment","groupInfo" +mGroupInfo);
        JSONObject object = null;
        try {
            object = new JSONObject(mGroupInfo.contact_card);
            mPhone = mGroupInfo.contact_phone;
            mName = mGroupInfo.contactName;
            mLimitPhone = mGroupInfo.phone_purview;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // TODO 此处必须先判断得到数据里有没有公司或者职位的字段
        try {

            if (object != null && object.has("organization")) {
                mCompany = object.getString("organization");
            } else {
                mCompany = "";
            }

            if (object.has("jobtitle")) {

                mPosition = object.getString("jobtitle");
            } else {
                mPosition = "";
            }
            if (object.has("demails")) {

                JSONObject emailObject = object.getJSONObject("demails");
                StringBuilder email = new StringBuilder();
                if (emailObject.has("_$!<Work>!$_")) {
                    email.append(emailObject.getString("_$!<Work>!$_"));
                }
                if (emailObject.has("_$!<Home>!$_")) {
                    email.append("  " + emailObject.getString("_$!<Home>!$_"));
                }
                mEmail = email.toString();

            } else {
                mEmail = "";
            }
/*部门字段目前没了
            if (object.has("department")) {
                mCloudContactDepartment = object.getString("department");
            } else {
                mCloudContactDepartment = "";
            }
*/

            // 解析地址信息，有两种情况，一种是按原手机通讯录上传格式，一种是后来设置的方式，只有_$!<Work>!$_字段
            mAddress = new StringBuilder();
            if (object.has("daddresses")) {
                JSONObject address = object.getJSONObject("daddresses");
                JSONObject add = address.getJSONObject("_$!<Work>!$_");
                if (add.has("City")) {
                    mAddress.append(add.getString("City"));
                }
                if (add.has("State")) {
                    mAddress.append(add.getString("State"));
                }
                if (add.has("Street")) {
                    mAddress.append(add.getString("Street"));
                }
                if (add.has("ZIP")) {
                    mAddress.append(add.getString("ZIP"));
                }
                if (add.has("Country")) {
                    mAddress.append(add.getString("Country"));
                }

            }
        } catch (JSONException e) {
            try {
                if (object.has("daddresses")) {
                    JSONObject address = object.getJSONObject("daddresses");
                    mAddress.append(address.getString("_$!<Work>!$_"));
                }
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }


        // 公司
        if (!StringUtil.isEmpty(mCompany)) {
            mTvCompany.setText(mCompany);
        }
        /*部门字段目前没了
        if (!StringUtil.isEmpty(mCloudContactDepartment)) {
            mTvContactDepartment.setVisibility(View.VISIBLE);
            mTvContactDepartment.setText(mCloudContactDepartment);
        } else {
            mTvContactDepartment.setVisibility(View.GONE);
        }
*/

        // 职位
        if (!StringUtil.isEmpty(mPosition)) {
            mTvPosition.setVisibility(View.VISIBLE);
            mTvPosition.setText(mPosition);
        } else {
            mTvPosition.setText("资料未完善");
        }

        // 邮箱
        if (!StringUtil.isEmpty(mEmail)) {
            mTvEmail.setText(mEmail);
        } else {
            mTvEmail.setText("资料未完善");
        }

        if (!StringUtil.isEmpty(mName)) {
            mTvName.setText(mName);
        } else {
            mTvName.setText("无名称");
        }

        // 办公地址
        if (!StringUtil.isEmpty(mAddress.toString())) {
            mTvAddress.setText(mAddress.toString());
        } else {
            mTvAddress.setText("资料未完善");

        }

       /* // 备注
        if (!StringUtil.isEmpty(mCloudContactNote)) {
            mTvContactNote.setText("  " + mCloudContactNote);
        } else {
            mTvContactNote.setText("暂无个人信息");
        }*/

        // 状态
       /* String uid = mGroupInfo.userId;
        if (!uid.equals("0")) {
            mIvStatus.setVisibility(View.VISIBLE);
        } else {
            mIvStatus.setVisibility(View.GONE);
        }
*/
        // 电话
        if ("1".equals(mLimitPhone)) {//显示电话号码
            ArrayList<PhoneNumItem> contactPhoneNum = mGroupInfo.contactPhoneNum;
            if (contactPhoneNum != null && contactPhoneNum.size() > 0) {
                // TODO 判断手机号码的个数，一个显示一个，两个以上只显示两个
//            if (contactPhoneNum.size() == 1) {
                mTvPhone.setText(contactPhoneNum.get(0).phoneNum.toString().trim());
                mTvPhone.setTextColor(getResources().getColor(R.color.cloud_contact_detail_blue));
                mTvPhone.setOnClickListener(this);
//            } else if (contactPhoneNum.size() > 1) {
//                mContentLayout.removeAllViews();
//                for (int i = 0; i < 2; i++) {
//                    View cloudPhoneItem = getCloudPhoneItemView(contactPhoneNum.get(i).label, contactPhoneNum.get(i).phoneNum);
//                    mContentLayout.addView(cloudPhoneItem);
//                    mContentLayout.addView(addLine(Constants.dip2px(this, 15)));
//                }
//            }
            }
        } else {
            mTvPhone.setText("限制号码公开");
            mTvPhone.setTextColor(getResources().getColor(R.color.cloud_contact_detail_light));
        }
    }


    private void showCallDialog() {
        mDialogUtil.titleOneDialog(mTvPhone.getText().toString().trim(), "发短信", "打电话");
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {
                CommonCodeUtil.launchSendMessage(mActivity, mTvPhone.getText().toString().trim(), null);
                lDialog.dismiss();

            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                CommonCodeUtil.launchCallByNumber(mActivity, mTvPhone.getText().toString().trim());
                lDialog.dismiss();
            }
        });

    }


    public SendCardShakeListener initShake() {
        SendCardShakeListener shaker = new SendCardShakeListener(mActivity);
        shaker.setOnShakeListener(new SendCardShakeListener.OnShakeListener() {

            public void onShake() {
                if (!StringUtil.isEmpty(mTvPhone.getText().toString().trim())) {
                    if ("1".equals(mLimitPhone)) {
                        CommonCodeUtil.launchCallByNumber(mActivity, mTvPhone.getText().toString().trim());
                    } else {
                        Toast.makeText(mActivity, "号码未公开", Toast.LENGTH_LONG).show();
                    }

                }
            }
        });
        return shaker;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_contact_namecard_phone:
                if ("1".equals(mLimitPhone)) {
                    showCallDialog();
                } else {
                    Toast.makeText(mActivity, "号码未公开", Toast.LENGTH_LONG).show();
                }

                break;
        }

    }


    @Override
    public void onResume() {
        super.onResume();
        if (mShaker != null) {
            mShaker.resume();
        } else {
            mShaker = initShake();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mShaker != null) {
            mShaker.pause();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mShaker != null) {
            mShaker.pause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mShaker != null) {
            mShaker.pause();
            mShaker = null;
        }
    }
}
